#-*-coding:utf-8-*-

import urllib2
import urllib
import cookielib
import sys
import json

class RenRen:
 
    def __init__(self, email, pwd, token=1674847503):
        self.email = email
        self.pwd = pwd
    
    def get(self, url):
        response = urllib2.urlopen(url).read()
        return response
        
    def post(self, url, values):
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        req.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; WindowsNT)")
        response = urllib2.urlopen(req).read()
        return response
 
    def login(self):
        cj = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)
 
        params = {"domain": "renren.com", "origURL": "http://www.renren.com/Home.do", "email": self.email, "password": self.pwd}
        req = urllib2.Request("http://www.renren.com/PLogin.do", urllib.urlencode(params))
        operate = opener.open(req)
        return operate.geturl() == "http://www.renren.com/home"
    
    def getFriendListById(self, id):
        url = "http://friend.renren.com/friendfriendSelector" + \
            "?p={'init':false,'qkey':'friend','uid':true,'uname':true,'uhead':false,'limit':1000,'param':{'guest':'%d'}}" % id
        response = self.get(url)
        data = json.loads(response)
        return data["candidate"]
        
    def addFriendById(self, id):
        url = "http://friend.renren.com/ajaxRequestFriendBatch"
        values = {"friends": id, "from": "sg_friendumayknow", "requestToken": self.token}
        return self.post(url, values)
    
    def getStatusComments(self, statusId, statusOwner):
        url = "http://status.renren.com/feedcommentretrieve.do"
        values = {"doingId": statusId, "owner": statusOwner, "requestToken": self.token, "source": statusId, "t": "3"}
        response = self.post(url, values)
        return json.loads(response)["replyList"]
        
    def postStatusComment(self, statusId, statusOwner, content):
        url = "http://status.renren.com/feedcommentreply.do"
        values = {"fin": "4", "ft": "status", "ff_id": statusOwner, "c": content, "t": "3", "doingId": "undefined",
                "feedId": "None", "owner": statusOwner, "requestToken": self.token, "rpLayer": "0", "source": statusId}
        response = self.post(url, values)

    def getStatusGenerator(self, userId):
        curpage = 0
        print userId
        base_url = "http://status.renren.com/GetSomeomeDoingList.do?userId="+str(userId)+"&curpage=%d"
        print base_url
        while True:
            print base_url % curpage
            data = json.loads(self.get(base_url % curpage))
            curpage = data["curpage"] + 1
            status_list = data["doingArray"]
            for status in status_list:
                yield status
            if curpage * 20 >= data["count"]:
                raise StopIteration  

    def getOnlineCount(self):
        data = json.loads(self.get("http://notify.renren.com/wpi/getonlinecount.do"))
        online_count = data["onlineFriendsCount"]
        return online_count
 
if __name__ == "__main__":
    #uname = raw_input("Please input username: ")
    #pwd = raw_input("Please input password")
    uname = "200814075"
    pwd = "2oo814o75"
    print "Login..."
    rr = RenRen(uname, pwd)
    login_success = rr.login()
    if login_success:
        print "Login success"
    else:
        print "Login failed"
    statuss = rr.getStatusGenerator(280215520)
    for status in statuss:
        print status["content"]
